<template>
  <div class="main-content">
    <div v-if="currentStep === 0">
      <div class="content">
        <div class="content_title">配置{{ productName }}</div>
        <div class="content_block">
          <configure-server
            ref="configureServer"
            :productId="productId"
            @changeTabKey="changeTabKey"
            @changeStationTab="changeStationTab"
            @changeGpuTabKey="changeGpuTabKey"
            @handleConfigureBase="handleConfigureBase"
            @handleAiImageType="handleAiImageType"
            @handleAiImageVersion="handleAiImageVersion"
            @handleSysImageType="handleSysImageType"
            @handleSysImageVersion="handleSysImageVersion"
            @handleStorageType="handleStorageType"
            @handleStorageSize="handleStorageSize"
            @handleFlexibleIpSize="handleFlexibleIpSize"
            @handleServerName="handleServerName"
          />
        </div>
      </div>
      <div class="footer">
        <count-footer-month
          v-if="tabKey === 'monthTab'"
          :baseCount="baseCount"
          :specFee="specFee"
          :storageCount="storageCount"
          :broadbandCount="broadbandCount"
          :flexibleIp="flexibleIp"
          @handleCountMonth="handleCountMonth"
          @handleCurrentStepBeforeCheck="handleCurrentStepBeforeCheck"
        />
        <count-footer-hour
          v-else
          :baseCount="baseCount"
          :specFee="specFee"
          :storageCount="storageCount"
          :broadbandCount="broadbandCount"
          :flexibleIp="flexibleIp"
          @handleCountHour="handleCountHour"
          @handleCurrentStepBeforeCheck="handleCurrentStepBeforeCheck"
        />
      </div>
    </div>
    <div v-if="currentStep === 1">
      <div class="content">
        <div class="content_title content_title_button">
          <div>请确认以下产品信息</div>
          <div class="content_title_more" @click="handleCurrentStep(0)">返回重新选择</div>
        </div>
        <div class="content_block">
          <sure-configure
            ref="sureConfigure"
            :stationTab="stationTab"
            :configureBase="configureBase"
            :aiImageType="aiImageType"
            :aiImageVersion="aiImageVersion"
            :sysImageType="sysImageType"
            :sysImageVersion="sysImageVersion"
            :storageType="storageType"
            :storageSize="storageSize"
            :flexibleIp="flexibleIp"
            :productName="productName"
            :serverNum="serverNum"
            :tabKey="tabKey"
            :timeNum="timeNum"
            :broadbandCount="broadbandCount"
            :baseCount="baseCount"
            :specFee="specFee"
            :storageCount="storageCount"
            :moneyCount="moneyCount"
          />
        </div>
      </div>
      <div class="footer">
        <count-footer-all
          :moneyCount="moneyCount"
          :tabKey="tabKey"
          @handleCurrentStepBeforePay="handleCurrentStepBeforePay"
        />
      </div>
    </div>
    <div v-if="currentStep === 2">
      <div class="content">
        <div class="content_title content_title_button">
          <div>支付</div>
        </div>
        <div class="content_block">
          <pay-order
            ref="payOrder"
            :orderId="orderId"
            :tabKey="tabKey"
            :canPayCount.sync="canPayCount"
            :canPayPassword.sync="canPayPassword"
          />
        </div>
      </div>
      <div class="footer">
        <count-footer-pay
          :canPayCount="canPayCount"
          :canPayPassword="canPayPassword"
          @handleCurrentStepBeforeSuccess="handleCurrentStepBeforeSuccess"
        />
      </div>
    </div>
    <div v-if="currentStep === 3">
      <order-result></order-result>
    </div>
  </div>
</template>

<script>
import CountFooterHour from '@/components/Product/CloudServer/CountFooterHour'
import CountFooterMonth from '@/components/Product/CloudServer/CountFooterMonth'
import ConfigureServer from '@/components/Product/CloudServer/ConfigureServer'
import SureConfigure from '@/components/Product/CloudServer/SureConfigure'
import CountFooterAll from '@/components/Product/CloudServer/CountFooterAll'
import PayOrder from '@/components/Product/CloudServer/PayOrder'
import CountFooterPay from '@/components/Product/CloudServer/CountFooterPay'
import OrderResult from '@/components/Product/CloudServer/OrderResult'
import store from '@/store'
import { mapState, mapActions } from 'vuex'
import { orderPay } from '@/api/Product/cloudServer'
export default {
  name: 'CloudServer',
  components: {
    CountFooterHour,
    CountFooterMonth,
    ConfigureServer,
    SureConfigure,
    CountFooterAll,
    PayOrder,
    CountFooterPay,
    OrderResult
  },
  data() {
    return {
      orderId: null,
      tabKey: 'monthTab', // 按周期购买的标签
      stationTab: null, // 站点的标签
      gpuTab: null, // GPU的标签
      configureBase: null, // 具体选择的GPU
      aiImageType: null, // AI框架
      aiImageVersion: null, // AI版本信息
      sysImageType: null, // 系统
      sysImageVersion: null, // 系统版本信息
      storageType: null, // 存储类型
      storageSize: 20, // 存储大小
      flexibleIp: null,
      serverName: '', // 服务器名称
      // productName: null, // 产品名称
      mirroringDTO: null, // 镜像id
      // 以下是具体钱的信息
      serverNum: 1, // 购买的服务器台数
      timeNum: 1, // 购买的时长，不带单位，周期方式为'月'、使用量方式为空
      baseCount: 0, // 配置费用（包含存储+规格）
      specFee: 0, // 规格费用
      storageCount: 0, // 存储费用
      broadbandCount: 0, // 带宽费用
      moneyCount: 0, // 总费用
      currentStep: 0, // 购买步骤
      canPayCount: false, // 用来验证账号余额是否满足
      canPayPassword: false // 用来验证密码是否满足
    }
  },
  computed: {
    ...mapState({
      productId: state => state.cloudServer.productId || null, // 产品id
      productName: state => state.cloudServer.productName || null // 产品名称
    })
  },
  watch: {
    serverNum: function(newValue, oldvalue) {
      console.log(newValue, oldvalue)
      this.submitOrder()
    },
    timeNum: function(newValue, oldvalue) {
      console.log(newValue, oldvalue)
      this.submitOrder()
    }
  },
  created() {
    const obj = {
      productId: this.$route.query.productId,
      productName: this.$route.query.productName
    }
    store.dispatch('updateProductInfo', obj)
  },
  methods: {
    ...mapActions(['updateGpuTabList']),
    /**
     * 固定页脚的-时长计费的
     * value: 服务器数量
     */
    handleCountHour(value) {
      // 服务器台数与时长
      this.serverNum = value
      this.timeNum = null
    },
    /**
     * 固定页脚的-时长计费的
     * monthsValue: 购买时长
     * numsValue: 服务器数量
     */
    handleCountMonth(monthsValue, numsValue) {
      // 服务器台数与时长
      this.serverNum = numsValue
      this.timeNum = monthsValue
    },
    // 查询价格
    submitOrder() {
      if (!(this.stationTab && this.configureBase && this.storageType)) {
        this.resetCount()
        return
      }
      if (this.tabKey === 'monthTab') {
        // 这三个确定的情况下就可以计算价格
        const param = {}
        // 新加参数
        param.chargeType = 'SERVER'
        if (this.stationTab) param.stationId = this.stationTab.value
        if (this.configureBase) param.specConfigId = this.configureBase.id
        if (this.storageSize) param.storageSize = this.storageSize
        if (this.flexibleIp) param.bandwidth = this.flexibleIp
        if (this.timeNum) param.monthNum = this.timeNum
        if (this.serverNum) param.serverNum = this.serverNum
        param.publicIP = this.flexibleIp ? true : false
        store
          .dispatch('monthlyFee', param)
          .then(res => {
            if (res && res.statusCode === 500) {
              this.broadbandCount = 0
              this.baseCount = 0
              this.specFee = 0
              this.storageCount = 0
              this.moneyCount = 0
              this.$message.error(res.message || '价格计算错误，请联系管理员', 3)
            }
            const bandWidthFee = res.data && res.data.bandWidthFee !== undefined ? res.data.bandWidthFee : 0
            const configFee = res.data && res.data.configFee !== undefined ? res.data.configFee : 0
            const storageFee = res.data && res.data.storageFee !== undefined ? res.data.storageFee : 0
            const specFee = res.data && res.data.specFee !== undefined ? res.data.specFee : 0
            this.broadbandCount = Number(bandWidthFee) || 0
            this.baseCount = Number(configFee) || 0
            this.specFee = Number(specFee) || 0
            this.storageCount = Number(storageFee) || 0
            this.moneyCount = Number(bandWidthFee) + Number(configFee)
          })
          .catch(() => {
            this.broadbandCount = 0
            this.baseCount = 0
            this.specFee = 0
            this.storageCount = 0
            this.moneyCount = 0
            this.$message.error('价格计算错误，请联系管理员', 3)
          })
      } else {
        const param = {}
        param.chargeType = 'SERVER'
        if (this.stationTab) param.stationId = this.stationTab.value
        if (this.configureBase) param.specConfigId = this.configureBase.id
        if (this.storageSize) param.storageSize = this.storageSize
        if (this.flexibleIp) param.bandwidth = this.flexibleIp
        if (this.serverNum) param.serverNum = this.serverNum
        param.publicIP = this.flexibleIp ? true : false
        store
          .dispatch('hourFee', param)
          .then(res => {
            if (res && res.statusCode === 500) {
              this.broadbandCount = 0
              this.baseCount = 0
              this.specFee = 0
              this.storageCount = 0
              this.moneyCount = 0
              this.$message.error(res.message || '价格计算错误，请联系管理员', 3)
            }
            const bandWidthFee = res.data && res.data.bandWidthFee !== undefined ? res.data.bandWidthFee : 0
            const configFee = res.data && res.data.configFee !== undefined ? res.data.configFee : 0
            const storageFee = res.data && res.data.storageFee !== undefined ? res.data.storageFee : 0
            const specFee = res.data && res.data.specFee !== undefined ? res.data.specFee : 0
            this.broadbandCount = Number(bandWidthFee) || 0
            this.baseCount = Number(configFee) || 0
            this.specFee = Number(specFee) || 0
            this.storageCount = Number(storageFee) || 0
            this.moneyCount = Number(bandWidthFee) + Number(configFee)
          })
          .catch(() => {
            this.broadbandCount = 0
            this.baseCount = 0
            this.specFee = 0
            this.storageCount = 0
            this.moneyCount = 0
            this.$message.error('价格计算错误，请联系管理员', 3)
          })
      }
    },
    // tab变动时，价格需要归0
    resetCount() {
      this.baseCount = 0
      this.specFee = 0
      this.storageCount = 0
      this.moneyCount = 0
    },
    // 按周期和按月的tab切换
    changeTabKey(value) {
      this.tabKey = value
      if (value === 'monthTab') {
        this.serverNum = 1
        this.timeNum = 1
      } else {
        this.serverNum = 1
        this.timeNum = null
      }
    },
    // 站点的tab切换
    changeStationTab(value) {
      this.stationTab = value
      this.resetCount()
    },
    // GPU的tab切换，1、需要查询出站点下的所有GPU
    changeGpuTabKey(value) {
      this.gpuTab = value
      this.resetCount()
    },
    // GPU具体选择
    handleConfigureBase(value) {
      this.configureBase = value
      this.submitOrder()
    },
    // AI框架的select二级联动的选项
    handleAiImageType(value) {
      this.aiImageType = value
    },
    // AI框架的select二级联动的选项-子选项
    handleAiImageVersion(value) {
      this.aiImageVersion = value
    },
    // 操作系统框架的select二级联动的选项
    handleSysImageType(value) {
      this.sysImageType = value
    },
    // 操作系统框架的select二级联动的选项-子选项
    handleSysImageVersion(value) {
      this.sysImageVersion = value
    },
    // 存储类型
    handleStorageType(value) {
      this.storageType = value
    },
    // 存储大小
    handleStorageSize(value) {
      this.storageSize = value
      this.submitOrder()
    },
    // 弹性公网
    handleFlexibleIpSize(value) {
      this.flexibleIp = value
      this.submitOrder()
    },
    // 服务器名称
    handleServerName(value) {
      this.serverName = value
    },

    // 购买流程-判断所选条件是否都满足
    handleCurrentStepBeforeCheck() {
      let flag = true
      if (!this.stationTab) {
        flag = false
        this.$refs.configureServer.dispalyWarnStation = true
      }
      if (!this.gpuTab) {
        flag = false
        this.$refs.configureServer.dispalyWarnGpu = true
      }
      if (!this.configureBase) {
        flag = false
        this.$refs.configureServer.dispalyWarnRows = true
      }
      if (!this.aiImageVersion) {
        flag = false
        this.$refs.configureServer.dispalyWarnAi = true
      }
      if (!this.sysImageVersion) {
        flag = false
        this.$refs.configureServer.dispalyWarnSys = true
      }
      if (!this.storageType) {
        flag = false
        this.$refs.configureServer.dispalyWarnStorage = true
      }
      if (this.$refs.configureServer.dispalyWarnServerName) {
        flag = false
      }
      if (!this.baseCount && flag) {
        this.$message.error('价格计算错误，请联系管理员', 3)
        flag = false
      }
      if (flag) {
        // 需要根据镜像信息把镜像ID查出来，返回给后台在下订单
        // mirroringDTO: null, // 镜像id
        const param = {
          productId: this.productId,
          stationId: this.stationTab.value,
          osDicItemId: this.sysImageType.id,
          versionDicItemId: this.sysImageVersion.id,
          softwareDicItemId: this.aiImageType.id,
          softwareVersionDicItemId: this.aiImageVersion.id
        }
        store.dispatch('mirroringAll', param).then(res => {
          if (res && res.data && res.data.rows) {
            const obj = res.data.rows[0]
            if (obj === undefined) {
              this.$message.error('服务器未配置对应镜像，请联系管理员', 3)
            } else {
              this.mirroringDTO = {
                id: obj.id,
                name: obj.name,
                osName: obj.osName,
                osVersionName: obj.osVersionName,
                softwareName: obj.softwareName,
                softwareVersion: obj.softwareVersion
              }
              // 跳转到下一步
              this.handleCurrentStep(1)
            }
          } else {
            this.$message.error('查询对应镜像出错，请联系管理员', 3)
          }
        })
      }
    },
    handleCurrentStepBeforePay() {
      const that = this
      let flag = true
      if (!this.$refs.sureConfigure.checked) {
        flag = false
        this.$refs.sureConfigure.dispalyWarnCheck = true
      }
      if (flag) {
        // 组件下订单的数据
        const param = {}
        param.productId = this.productId
        param.typeId = 0 // 订单类型 0-购买 1-续费 2-退费【必须】"
        param.chargeType = this.tabKey === 'monthTab' ? 0 : 1 //计费方式 0-包年包月 1-按小时计费【必须】"
        param.stationId = this.stationTab.value
        param.stationName = this.stationTab.name
        const configureBase = this.configureBase
        param.specConfigDTO = {
          id: configureBase.id,
          name: configureBase.name,
          resourcePoolId: configureBase.resourcePoolId,
          cpuCore: configureBase.cpuCore,
          memoryCapacity: configureBase.memoryCapacity,
          acceleratorTypeId: configureBase.acceleratorTypeId,
          acceleratorNumber: configureBase.acceleratorNumber
        }
        param.mirroringDTO = this.mirroringDTO
        param.storageTypeId = this.storageType.id
        param.storageCapacity = this.storageSize
        param.isAllocatedIP = this.flexibleIp ? 1 : 0 // 是否分配弹性公网IP 0-不分配 1-分配【必须】"
        param.networkBandwidth = this.flexibleIp ? this.flexibleIp : 0 // 公网带宽（不分配默认就是0）【必须】"
        param.serverName = this.serverName
        param.purchaseTime = this.timeNum
        param.productNumber = this.serverNum
        const configInfoObj = {
          stationName: this.stationTab.name || '',
          configureBase:
            this.configureBase.gpuProductName +
            ' (' +
            this.configureBase.cpuSize +
            'CPU, ' +
            this.configureBase.memorySize +
            'GB内存, ' +
            this.configureBase.gpuTypeValue +
            ')',
          aiInfo: this.aiImageType.name + ' ' + this.aiImageVersion.name,
          osInfo: this.sysImageType.name + ' ' + this.sysImageVersion.name,
          storageInfo: this.storageType.name + ' ' + this.storageSize + 'G',
          ipInfo: this.flexibleIp ? `公网IP（ ${this.flexibleIp}M )` : ''
        }
        const configInfo = JSON.stringify(configInfoObj)
        const transactionInfoObj = {
          规格费用: this.specFee, // 规格的价格
          配置费用: this.baseCount, // 配置费用的价格
          存储费用: this.storageCount, // 存储的价格
          宽带费用: this.broadbandCount, // 宽带配置的费用价格
          合计费用: this.moneyCount // 总价格
        }
        const transactionInfo = JSON.stringify(transactionInfoObj)
        param.configInfo = configInfo
        param.price = this.moneyCount
        param.transactionInfo = transactionInfo
        store
          .dispatch('cloudServerAdd', [param])
          .then(res => {
            if (res && res.statusCode === 500) {
              this.$message.error(res.message || '后端异常，请联系管理员', 3)
            } else {
              const orderId = res.data ? res.data[0] : null
              that.orderId = orderId
              this.handleCurrentStep(2)
            }
          })
          .catch(() => {
            this.$message.error('后端异常，请联系管理员', 3)
          })
        store.dispatch('GetInfo')
      }
    },
    handleCurrentStepBeforeSuccess() {
      if (this.canPayPassword && this.canPayCount) {
        const param = {
          payPassword: this.$refs.payOrder.pwdList.join(''),
          productName: this.productName,
          productNumber: this.serverNum,
          orderId: this.orderId,
          price: this.moneyCount,
          payType: '3',
          chargeType: this.tabKey === 'monthTab' ? 0 : 1 //计费方式 0-包年包月 1-按小时计费【必须】"
        }
        orderPay([param]).then(res => {
          if (res && res.data) {
            // int，1成功；2没有设置支付密码；3密码输入错误(如果只有0次了也返回)；4订单支付时间过期
            const status = res.data.status || 1
            if (status === 1) {
              this.handleCurrentStep(3)
              store.dispatch('GetInfo')
            } else if (status === 2) {
              const str = '请先设置支付密码'
              this.canPayPassword = false
              this.$refs.payOrder.message = str
            } else if (status === 3) {
              const count = res.data.count || 0
              if (count === 0) {
                this.$message.error('密码连续输错，已锁定', 2)
                setTimeout(() => {
                  this.$router.push({ path: '/home' })
                }, 2000)
              }
              const str = '支付密码不正确，您还可以尝试' + count + '次'
              this.$refs.payOrder.message = str
            } else if (status === 4) {
              this.$message.error('订单支付时间过期', 2)
              setTimeout(() => {
                this.$router.push({ path: '/home' })
              }, 2000)
            } else if (status === 5) {
              this.$message.error('账户余额不足', 2)
              store.dispatch('GetInfo')
              setTimeout(() => {
                this.$router.push({ path: '/home' })
              }, 2000)
            }
          } else if (res && res.statusCode && res.statusCode === 200) {
            this.handleCurrentStep(3)
            store.dispatch('GetInfo')
          } else {
            this.$message.error(res.message || '服务异常', 2)
            // this.$router.push({ path: '/home' })
          }
        })
      }
    },
    // 购买流程
    handleCurrentStep(value) {
      this.currentStep = value
      if (value === 0) {
        // 所有数据刷新
        Object.assign(this.$data, this.$options.data())
        // GPU类型也要清空
        this.updateGpuTabList([])
      }
    }
  }
}
</script>

<style lang="less" scoped>
.main-content {
  width: 100%;
  min-height: calc(100vh - 60px);
  position: relative;
  font-weight: normal;
  font-stretch: normal;
  letter-spacing: 0px;
  .content {
    z-index: 1;
    width: 100%;
    padding: 0 30px 116px 30px; // 下面的是固定页脚，需要超过这个116px
    .content_title {
      font-size: 18px;
      line-height: 18px;
      color: #333333;
      padding: 30px;
    }
    .content_title_button {
      display: flex;
      align-items: center;
      justify-content: flex-start;
      .content_title_more {
        width: 112px;
        height: 30px;
        line-height: 30px;
        text-align: center;
        margin-left: 15px;
        background-color: #e6f2ff;
        border-radius: 2px;
        border: solid 1px #75c6ee;
        font-size: 12px;
      }
      .content_title_more:hover {
        cursor: pointer;
        color: #33b0ed;
      }
    }
    .content_block {
      width: 100%;
    }
  }
  .footer {
    width: 100%;
    position: fixed;
    bottom: 0;
    z-index: 99;
  }
}
</style>
